import * as express from 'express';
import {Request, Response, NextFunction} from 'express';
import {ConnPoolInstance} from '../AppDatabase';

export enum RouterType{
    Get,
    Post
}

export abstract class BaseController {
    protected routerUrl: string;
    protected request: express.Request;
    protected response: express.Response;
    protected nextFun: express.NextFunction;
    protected postJson: any;

    // 子类的入口函数
    public abstract Start(): void;

    public  InitRouter(routerUrl: string, type: RouterType = RouterType.Get ): express.Router{
        this.routerUrl = routerUrl;

        // 将 routerUrl 路由到 GetHandler() 函数中
        let router = express.Router();
        if (type == RouterType.Get){
            router.get(this.routerUrl, this.Handler.bind(this));
        }else{
            router.post(this.routerUrl, this.Handler.bind(this));
        }

        return router;
    }

    public async Handler(req: express.Request, res: express.Response, next: express.NextFunction) {
        this.request = req;
        this.response = res;
        this.nextFun = next;

        try{
            await this.Start();
        }catch(e){
            this.ErrorHandler(e);
        }
    }

    // 默认的错误处理函数，返回错误信息
    public ErrorHandler(msg: string, res?: Response){
        if (res == null){
            res = this.response;
        }
        let json = {
            error: msg
        };
        
        res.send(JSON.stringify(json));
    }

    public GetUnixTime(): number{
        return Math.floor(new Date().getTime() / 1000);
    }

    async WriteOrderInfoToDb(channelId: number, 
        channelName: string, orderId: string, p_type: number, uid: number, 
        money: number, gamemoney: number, time: number, extra: string, 
        verfiySign: number) : Promise<number>
    {
        let sql = "INSERT INTO payment_log SET ?";
        let data = {
            channelId: channelId,
            channelName: channelName,
            orderId: orderId,
            p_type: p_type,
            uid: uid,
            money: money, 
            gamemoney: gamemoney,
            time: time,
            extra: extra,
            verifySign: verfiySign
        };
        
        let ret = await ConnPoolInstance.Insert(sql, data);

        return ret;
    }

    public CheckAndParserJson(){
        let body = this.request.body;
        try{
            this.postJson = JSON.parse(body);
        }catch(e){
            e.message = "parser data error: " + body; 
            throw e;
        }
    }
}


